#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
queue<int>q;
struct edge{int x,y;}w[200010];
int i,j,k,n,m,x,y,t;
int s[200010],low[200010],dfn[200010];
int fi[200010],ne[200010],la[200010],a[200010];
int v[200010],vis[200010],num,T;
int cnt,p[200010],d[200010],ins[200010];
long long sum[200010],f[200010],ans;
void add(int x,int y){
    k++;a[k]=y;
    if (fi[x]==0)fi[x]=k;else ne[la[x]]=k;
    la[x]=k;
}
void tarjan(int x){
    ins[x]=1;low[x]=dfn[x]=++num;
    s[++s[0]]=x;
    for (int i=fi[x];i;i=ne[i])
        if (!dfn[a[i]]){
            tarjan(a[i]);
            low[x]=min(low[x],low[a[i]]);
        }
        else if (ins[a[i]])low[x]=min(low[x],dfn[a[i]]);
    if (dfn[x]==low[x]){
        ++cnt;
        while (s[s[0]]!=x){
            p[s[s[0]]]=cnt;sum[cnt]+=1;ins[s[s[0]]]=0;
            s[0]--;
        }
        p[x]=cnt;sum[cnt]+=1;ins[x]=0;s[0]--;
    }
}
int main(){
    scanf("%d",&T);
    while (T--){
        k=0;cnt=0;
        memset(fi,0,sizeof fi);
        memset(ne,0,sizeof ne);
        memset(la,0,sizeof la);
        memset(sum,0,sizeof sum);
        memset(f,0,sizeof f);
        memset(dfn,0,sizeof dfn);
        memset(low,0,sizeof low);
        memset(d,0,sizeof d);
        ans=0;
        scanf("%d%d",&n,&m);
        for (i=1;i<=m;i++){
            scanf("%d%d",&x,&y);
            w[i]=(edge){x,y};
            add(x,y);
        }
        for (i=1;i<=n;i++)
            if (!dfn[i]){
                tarjan(i);
            }
        k=0;
        memset(fi,0,sizeof fi);
        memset(ne,0,sizeof ne);
        memset(la,0,sizeof la);
        for (i=1;i<=m;i++){
            if (p[w[i].x]!=p[w[i].y]){
                x=p[w[i].x];y=p[w[i].y];
                add(x,y);
                d[y]++;
            }
        }
        for (i=1;i<=cnt;i++)if (d[i]==0)q.push(i);
        while (!q.empty()){
            x=q.front();q.pop();
            ans=max(ans,f[x]+sum[x]);
            for (int i=fi[x];i;i=ne[i]){
                f[a[i]]=max(f[a[i]],f[x]+sum[x]);
                d[a[i]]--;
                if (!d[a[i]])q.push(a[i]);
            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}